#include <stdio.h>
#include <limits.h>
#include <errno.h>
#include <string.h>

#include "prop.h"

FILE *g_file=NULL;
char g_env[PATH_MAX] = {0};

void propSepToSpace(char *env, char *env2)
{
  char *sep;

  strcpy(env2, env);
  
  while ((sep = strchr(env2, '\xFF')))
    *sep = ' ';
}

int propInit(char *name)
{
  if (g_file)
    propFini();

  g_file = fopen(name, "w");
  
  if (!g_file)
    return -errno;

  fprintf(g_file, "<document>\n");
  
  propEnvReset();

  return 0;
}

void propEnv(char *env, char *obj)
{
  if (g_env[0])
    strcat(g_env, "\xFF");

  sprintf(&g_env[strlen(g_env)], "%s = \"%s\"", env, obj);
}

void propEnvBack(void)
{
  char *sep = strrchr(g_env, '\xFF');
  
  if (sep)
    *sep = 0;
}

void propEnvReset(void)
{
  g_env[0] = 0;
}

void propSeti(char *prop, int value)
{
  char env[PATH_MAX];

  if (!g_file) return;
  
  propSepToSpace(g_env, env);
  fprintf(g_file, "  <env %s>\n    <E %s = \"%d\"/>\n  </env>\n",
          env, prop, value);
}

void propSetf(char *prop, double value)
{
  char env[PATH_MAX];
  
  if (!g_file) return;

  propSepToSpace(g_env, env);
  fprintf(g_file, "  <env %s>\n    <E %s = \"%f\"/>\n  </env>\n",
          env, prop, value);
}

void propSets(char *prop, char *value)
{
  char env[PATH_MAX];
  
  if (!g_file) return;

  propSepToSpace(g_env, env);
  fprintf(g_file, "  <env %s>\n    <E %s = \"%s\"/>\n  </env>\n",
          env, prop, value);
}

void propFini(void)
{
  if (!g_file) return;

  fprintf(g_file, "</document>\n");

  fclose(g_file);
}
